package com.educationagent.controller;

import com.educationagent.service.AgentService;
import com.educationagent.service.impl.AgentServiceImpl;
import com.educationagent.util.MultipartFileDocumentSource;
import com.educationagent.util.Result;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentLoader;
import dev.langchain4j.data.document.DocumentSource;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.parser.apache.pdfbox.ApachePdfBoxDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.embedding.onnx.HuggingFaceTokenizer;
import dev.langchain4j.store.embedding.EmbeddingStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.CompletableFuture;


@RestController
@RequestMapping("/agent")
public class AgentController{

    // 本地运行:文件上传,下载目录
    //private static final String UPLOAD_DIR = "D:/agent/uploadPath";

    // linux运行:文件上传,下载目录
    private static final String UPLOAD_DIR = "/home/luozihao/jdk/file";

    //本地改成localhost,线上改为60.204.171.10    文件请求url
    private static final String BASE_URL = "http://60.204.171.10:8080/agent";
    private static final Logger log = LoggerFactory.getLogger(AgentController.class);


 /*   @Autowired
    private EmbeddingModel embeddingModel;

    @Autowired
    private EmbeddingStore embeddingStore;*/

    @Autowired
    private AgentServiceImpl agentServiceImpl;


    //文档上传
    @PostMapping(value = "/document")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException, InterruptedException {

        if (file.isEmpty()) {
            return Result.fail("上传文件为空");
        }

        //检查文件头部字节 (PDF 文件以 %PDF 开头)
        byte[] bytes = file.getBytes();
        boolean hasPdfHeader = bytes.length >= 4 &&
                bytes[0] == 0x25 &&
                bytes[1] == 0x50 &&
                bytes[2] == 0x44 &&
                bytes[3] == 0x46;
        if (!hasPdfHeader) {
            return Result.fail("文件格式错误");
        }


        Path uploadPath = Paths.get(UPLOAD_DIR);

        // 确保目录存在
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名（避免重名）
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        Path filePath = uploadPath.resolve(fileName);

        // 保存文件
        file.transferTo(filePath.toFile());

        // 构建下载URL（对文件名进行URL编码，避免特殊字符问题）
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        String downloadUrl =  BASE_URL + "/download/" + encodedFileName;

        CompletableFuture<Boolean> future = agentServiceImpl.longRunningMethod(downloadUrl);
        future.thenAccept(result  -> {
            if (result){
                log.info("文档向量化成功");
            }else {
                log.info("文档向量化失败");
            }

        });

        return Result.success(downloadUrl,"文件保存成功");

    }


    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            // 解码路径中的文件名（如上传时存储的UUID文件名）
            String decodedStorageName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);

            // 构建文件路径（假设存储名为UUID_原始文件名.pdf）
            Path filePath = Paths.get(UPLOAD_DIR).resolve(decodedStorageName);
            Resource resource = new FileSystemResource(filePath);

            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 提取原始文件名（假设存储名格式为 "UUID_原始文件名.pdf"）
            String originalFileName = decodedStorageName.split("_", 2)[1]; // 拆分UUID和原始名

            // 按RFC 5987编码文件名
            String encodedFileName = URLEncoder.encode(originalFileName, StandardCharsets.UTF_8)
                    .replaceAll("\\+", "%20"); // 替换加号为空格

            // 设置合规的Content-Disposition头
            ContentDisposition contentDisposition = ContentDisposition.attachment()
                    .filename(originalFileName, StandardCharsets.UTF_8) // 自动生成filename*字段
                    .build();

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }


}
